package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperUtils {
    private MapperUtils(){}

    //线程域对象，保存当前线程的SqlSession，方便释放
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    private static SqlSessionFactory factory;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSqlSession(boolean autoCommit){
        return factory.openSession(autoCommit);
    }

    public static SqlSession openSqlSession(){
        return openSqlSession(false);
    }

    public static <T> T getMapper(Class<T> cls){
        SqlSession sqlSession = openSqlSession();
        tl.set(sqlSession);
        T mapper = sqlSession.getMapper(cls);
        return mapper;
    }

    public static void close(){
        SqlSession session = tl.get();
        session.close();
        tl.remove();
    }

    public static void commit(){
        SqlSession session = tl.get();
        session.commit();
    }
    public static void rollback(){
        SqlSession session = tl.get();
        session.rollback();
    }
}
